package me.softwareengineer.guice.rendering.domain;

import java.util.List;
import java.util.Map;

import me.softwareengineer.guice.rendering.listener.EndSectionEvent;
import me.softwareengineer.guice.rendering.listener.Listener;
import me.softwareengineer.guice.rendering.listener.StartSectionEvent;

/**
 * Represents section block. Document sections delimits a set of structural
 * elements at the same "level". A new level starts with a new document or a new
 * header.
 * 
 * <pre>
 * Examples : - document with two headers (one section into another)
 * -------------------------------+--------------------------------------------
 * Source                         |  Result
 * -------------------------------+--------------------------------------------
 *  = First Header =              |+ section0
 *  First paragraph.              |  + document 
 *  == Second Header ==           |  + sectionContent0
 *  Second paragraph.             |    + section1
 *                                |      + header1 = First Header
 *                                |      + sectionContent1
 *                                |        + paragraph = First paragraph.
 *                                |        + section2
 *                                |          + header2 = Second Header
 *                                |          + sectionContent2
 *                                |            + paragraph = Second paragraph.
 * </pre>
 * 
 * @author yadtahir
 * @see HeaderElement <pre>
 * This class is thread-safe and can be cached/re-used and used concurrently.
 * </pre>
 */
public class SectionElement extends Element {

	/**
	 * Constructs a section element with no properties
	 * 
	 * @param children
	 *            the children of the section
	 */
	public SectionElement(List<Element> children) {
		super(children);
	}

	/**
	 * Constructs a section element with the provided properties
	 * 
	 * @param children
	 *            the children of the section
	 * @param properties
	 *            the properties of the section
	 */
	public SectionElement(List<Element> children, Map<String, String> properties) {
		super(children, properties);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void afterElement(Listener l) {
		EndSectionEvent e = new EndSectionEvent(getAllProperties());
		l.onEvent(e);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void beforeElement(Listener l) {
		StartSectionEvent e = new StartSectionEvent(getAllProperties());
		l.onEvent(e);
	}

	/**
	 * @return the title block of the section.
	 */
	public HeaderElement getHeaderBlock() {
		HeaderElement headerBlock = null;

		List<Element> children = getChildren();

		if (children.size() > 0) {
			Element firstChild = children.get(0);
			if (firstChild instanceof HeaderElement) {
				headerBlock = (HeaderElement) firstChild;
			}
		}

		return headerBlock;
	}

}
